/**
 * ACL类, 用于搜索leancloud ACL相关对象.
 */
class $ACL {
  constructor(AV, handler, request, that) {
    this.AV = AV
    this.$http = new AV.ACL()
    this.request = request
    this.that = that
    this.avObject = null
  }

  setPublicReadAccess(allowed) {
    this.$http.setPublicReadAccess(allowed)
    this.avObject = this.$http
    return this
  }

  setPublicWriteAccess(allowed) {
    this.$http.setPublicWriteAccess(allowed)
    this.avObject = this.$http
    return this
  }

  setReadAccess(user, allowed) {
    this.$http.setReadAccess(user, allowed)
    this.avObject = this.$http
    return this
  }

  setWriteAccess(user, allowed) {
    this.$http.setWriteAccess(user, allowed)
    this.avObject = this.$http
    return this
  }

  setRoleReadAccess(role, allowed) {
    this.$http.setRoleReadAccess(user, allowed)
    this.avObject = this.$http
    return this
  }

  setRoleWriteAccess(role, allowed) {
    this.$http.setRoleWriteAccess(role, allowed)
    this.avObject = this.$http
    return this
  }

  // 个人定制API
  /**
   * 创建一个acl权限对象, 用于给object数据添加acl权限
   * @param {Object} controlGroup    控制权限值包括readUser, writeUser, readRole, writeRole
   * @param {Array} controlGroup.readUser   包含允许读取权限的用户objectId数组
   * @param {Array} controlGroup.writeUser  包含允许写入权限的用户objectId数组
   * @param {Array} controlGroup.readRole   包含允许读取权限的角色名称数组
   * @param {Array} controlGroup.writeRole  包含允许写入权限的角色名称数组
   * @return {Object} 当前ACL类 this.avObject为改创建的acl对象
   */
  createACL({ readUser, writeUser, readRole, writeRole }) {
    const { $http } = this
    readUser = readUser || true
    writeUser = writeUser || false
    if (readUser && readUser.length)
      readUser.forEach((item) => this.setReadAccess(item, true))
    else this.setPublicReadAccess(readUser)
    if (writeUser && writeUser.length)
      writeUser.forEach((item) => this.setWriteAccess(item, true))
    else this.setPublicWriteAccess(writeUser)
    if (readRole && readRole.length)
      readRole.forEach((item) => this.setRoleReadAccess(item, true))
    if (writeRole && writeRole.length)
      writeRole.forEach((item) => this.setRoleWriteAccess(item, true))
    this.avObject = $http
    return this
  }
}
export default $ACL
